#include <stdio.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <signal.h>
#include <pthread.h>

int main(int argc, char const *argv[])
{
    while(1)
    {
        // 1、创建一个TCP的客户端对象
        int tcp_socket = socket(AF_INET, SOCK_STREAM, 0);

        // 2、连接http服务器 42.192.160.185(青云客机器人http服务器地址)
        struct sockaddr_in server_addr;
        server_addr.sin_family      = AF_INET;   
        server_addr.sin_port        = htons(80);
        server_addr.sin_addr.s_addr = inet_addr("42.192.160.185");
        
        int ret = connect(tcp_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (ret < 0)
        {
            perror("connect error!\n");
            return -1;
        }
        
        // 3、发送http请求
        // http://api.qingyunke.com/api.php?key=free&appid=0&msg=你有男朋友吗？
        char http_request[2048] = {0};
        char chat_buf[1024]     = {0};
        printf("请输入要问的问题:\n");
        scanf("%s", chat_buf);

        // 拼接请求和提问
        sprintf(http_request, "GET /api.php?key=free&appid=0&msg=%s HTTP/1.1\r\nHost:api.qingyunke.com\r\n\r\n", chat_buf);
        write(tcp_socket, http_request, strlen(http_request));

        // 4、读取http服务器的应答数据
        char buf[4096] = {0};
        read(tcp_socket, buf, sizeof(buf));
        printf("服务器应答数据:%s\n", buf);

        // 5、关闭socket
        close(tcp_socket);

    }

    

    return 0;
}

